using System;
using System.Collections.Generic;
using System.Text;

namespace Lutos.CharMutant
{
    public class PinYinMap
    {
        public struct CharWeigh : IComparable<CharWeigh>
        {
            public CharWeigh(char ch, int weigh)
            {
                this.Ch = ch;
                this.Weigh = weigh;
            }
            public char Ch;
            public int Weigh;

            public int CompareTo(CharWeigh other)
            {
                return this.Weigh - other.Weigh;
            }
        }
        public PinYinMap()
        {
            
        }

        private Dictionary<string, List<CharWeigh>> py2ch = new Dictionary<string, List<CharWeigh>>();
        private Dictionary<char, string> ch2py = new Dictionary<char, string>();
        private Dictionary<char, int> ch2wh = new Dictionary<char, int>();
        public bool AddMap(char ch, string pinyin, int weigh)
        {
            if (ch2py.ContainsKey(ch))
                return false;
            List<CharWeigh> list;
            if(py2ch.TryGetValue(pinyin, out list))
            {
                foreach (CharWeigh cw in list)
                {
                    if(cw.Ch == ch)
                        return false;
                }
            }
            else
            {
                list = new List<CharWeigh>();
                py2ch.Add(pinyin, list);
            }
            CharWeigh chw = new CharWeigh(ch, weigh);
            int i = list.BinarySearch(chw);
            if(i<0)
                i = ~i;
            list.Insert(i, chw);
            ch2py.Add(ch, pinyin);
            ch2wh.Add(ch, weigh);
            return true;
        }

        public IList<CharWeigh> this[string pinyin]
        {
            get
            {
                List<CharWeigh> list;
                if (py2ch.TryGetValue(pinyin, out list))
                {
                    return list.AsReadOnly();
                }
                return new CharWeigh[0];
            }
        }

        public string this[char ch]
        {
            get
            {
                string pinyin;
                if(ch2py.TryGetValue(ch, out pinyin))
                {
                    return pinyin;
                }
                return null;
            }
        }

        public int GetWeigh(char ch)
        {
            return ch2wh[ch];
        }

        public bool ContainsChar(char ch)
        {
            return ch2py.ContainsKey(ch);
        }
    }
}
